// ignore_for_file: use_build_context_synchronously

import 'package:aitao_flutter/utils/log_utils.dart';
import 'package:aitao_flutter/utils/oss_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../model/certification_model.dart';
import '../../request/api.dart';
import '../../request/requestManager.dart';

class CertificationController extends GetxController {
  bool isLoading = true;
  CertificationModel? certificationModel;
  int updateType = 0; // 0:上传认证图 1:上传头像

  List<Map> desList = [
    {'title': '示例图', 'des': '（按照图中手势）'},
    {'title': '认证照', 'des': '（不对外展示）'},
    {'title': '示例图', 'des': '（露全脸，背景清晰）'},
    {'title': '头像', 'des': '（露全脸，背景清晰）'}
  ];
  @override
  void onInit() {
    super.onInit();
    getCertificationData();
  }

  void getCertificationData() async {
    var result = await RequestManager().post(API.applyStatus);
    if (result != null && result['code'] == 0) {
      WJLogUtils.wjLog(result);
      isLoading = false;
      certificationModel = CertificationModel.fromJson(result['data']);
      update();
    }
  }

  void updateCaremaClick(BuildContext context) async {
    if (certificationModel?.inAudit == 1) {
      EasyLoading.showToast('您已提交认证,请耐心等待审核.');
      return;
    }
    updateType = 0;
    checkPermission(context);
  }

  void checkPermission(BuildContext context) async {
    Permission permission = Permission.storage;
    PermissionStatus status = await permission.status;
    if (status.isGranted) {
      openPicker(context);
    } else if (status.isDenied) {
      //权限拒绝， 需要区分IOS和Android，二者不一样
      requestPermission(permission, context);
    } else if (status.isPermanentlyDenied || status.isRestricted) {
      //权限永久拒绝，且不在提示，需要进入设置界面，IOS和Android不同
      showDialog<String>(
        context: context,
        builder: (BuildContext context) => AlertDialog(
          title: const Text('你已关闭手机相册相册权限'),
          content: const Text('请到手机设置开启相册权限'),
          actions: <Widget>[
            // if user deny again, we do nothing
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('不开启'),
            ),

            // if user is agree, you can redirect him to the app parameters :)
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                openAppSettings();
              },
              child: const Text('去开启'),
            ),
          ],
        ),
      );
    } else {
      //第一次申请
      requestPermission(permission, context);
    }
  }

  void requestPermission(Permission permission, BuildContext context) async {
    //发起权限申请
    PermissionStatus status = await permission.request();
    // 返回权限申请的状态 status
    if (status.isPermanentlyDenied) {
      //权限永久拒绝，且不在提示，需要进入设置界面，IOS和Android不同
      showDialog<String>(
        context: context,
        builder: (BuildContext context) => AlertDialog(
          title: const Text('你已关闭手机相册相册权限'),
          content: const Text('请到手机设置开启相册权限'),
          actions: <Widget>[
            // if user deny again, we do nothing
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('不开启'),
            ),

            // if user is agree, you can redirect him to the app parameters :)
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                openAppSettings();
              },
              child: const Text('去开启'),
            ),
          ],
        ),
      );
    }
  }

  void openPicker(BuildContext context) async {
    AssetPickerConfig config =
        const AssetPickerConfig(maxAssets: 1, requestType: RequestType.image);
    final List<AssetEntity>? entitys =
        await AssetPicker.pickAssets(context, pickerConfig: config);
    // final List<AssetEntity>? entitys = await AssetPicker.pickAssets(context)
    if (entitys == null) return;
    EasyLoading.show(status: '上传中...');
    String result = await UploadOss.uploadImages(entitys);
    if (updateType == 0) {
      certificationModel?.applyCamara = result;
    } else {
      certificationModel?.applyAvatar = result;
    }

    update();
    EasyLoading.dismiss();
    debugPrint('图片上传结果result:$result');
  }

  void updateAvatarClick(BuildContext context) async {
    if (certificationModel?.inAudit == 1) {
      EasyLoading.showToast('您已提交认证,请耐心等待审核.');
      return;
    }
    updateType = 1;
    checkPermission(context);
  }

  void submitClick() async {
    if (certificationModel?.inAudit == 1) {
      EasyLoading.showToast('您已提交认证,请耐心等待审核.');
      return;
    }
    if (certificationModel?.applyCamara == '') {
      EasyLoading.showToast('请上传自拍照');
      return;
    }
    if (certificationModel?.applyAvatar == '') {
      EasyLoading.showToast('请上传头像');
      return;
    }
    Map params = {
      'camara_demo': certificationModel?.demoCamara,
      'avatar': certificationModel?.applyAvatar,
      'camara': certificationModel?.applyCamara
    };
    var result = await RequestManager().post(API.addApply, params: params);
    if (result != null && result['code'] == 0) {
      EasyLoading.showToast(result['message']);
      Get.back();
    }
  }
}
